package com.mai4j.maiadmin.service.impl;

import com.mai4j.maiadmin.model.dto.CurrencyDTO;
import com.mai4j.maiadmin.service.CurrencyService;
import com.mai4j.maiadmin.service.ExchangeRateService;
import com.mai4j.maiadmin.service.SettingService;
import org.javamoney.moneta.Money;
import org.springframework.stereotype.Service;

import javax.money.MonetaryAmount;
import javax.money.convert.CurrencyConversion;
import javax.money.convert.MonetaryConversions;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Service
public class ExchangeRateServiceImpl implements ExchangeRateService {

    private final CurrencyService currencyService;

    private final SettingService settingService;

    public ExchangeRateServiceImpl(CurrencyService currencyService, SettingService settingService) {
        this.currencyService = currencyService;
        this.settingService = settingService;
    }

    @Override
    public int update() {
        List<CurrencyDTO> list = currencyService.list();
        String src = (String) Optional.ofNullable(settingService.get("config").get("currency")).orElse("CNY");
        AtomicInteger i = new AtomicInteger();
        list.forEach(currencyDTO -> {
            try {
                String dest = currencyDTO.getCode();
                double v = src.equals(dest) ? 1.0000d : conv(src, dest);
                currencyService.updateValue(currencyDTO.getCurrencyId(), new BigDecimal(v));
                i.getAndIncrement();
            } catch (Exception ignore) {
            }
        });
        return i.get();
    }

    /**
     * @param src  本币
     * @param dest 原币
     * @return value
     */
    private double conv(String src, String dest) {
        MonetaryAmount amt = Money.of(1, src);
        CurrencyConversion conv = MonetaryConversions.getConversion(dest, "ECB", "IMF");
        return amt.with(conv).getNumber().doubleValue();
    }

}
